package com.fingard.dsp.bank.directbank.gynsh01.util;

import java.io.IOException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.xml.security.utils.Base64;

/**
 * @Description TODO
 * @Author xtt
 * @Date $ $
 **/
public class JsonHelper {


    public static String decrypted(String resStr,String privateKeyMerchant) throws Exception{
        JSONObject jsonObject = JSON.parseObject(resStr);
        byte[] encryptedData = Base64.decode(jsonObject.getString("body"));
        System.out.println(encryptedData);
        String decrypted = SecurityUtils.decryptByMerchantPrivateKey(encryptedData,privateKeyMerchant);
        return decrypted;
    }

    /*
    public static Object post(String url, String data) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity dataEntity = new StringEntity((String) data, ContentType.APPLICATION_JSON);
        httpPost.setEntity(dataEntity);
        return postSend(httpPost);
    }*/

    public static String postSend(String url, String data) {
        HttpPost httpPost = new HttpPost(url);
        StringEntity dataEntity = new StringEntity((String) data, ContentType.APPLICATION_JSON);
        httpPost.setEntity(dataEntity);
        CloseableHttpClient httpClient = HttpClients.createDefault();// 如果不采用连接池就是这种方式获取连接
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String resopnse = "";
            if (entity != null) {
                resopnse = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            return entity != null ? resopnse : null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpPost != null) {
                httpPost.abort();
            }
            if (response != null) {
                try {
                    response.close();// 关闭响应,迅速的关闭并丢弃连接
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static JSONObject createBankBizCont(JSONObject jsonObj,String privateKeyMerchant,String publicKeyBank) throws Exception {
        JSONObject bodyObj = new JSONObject();
        // 银行公钥加密
        String sortedByKey = sortByKey(jsonObj.toJSONString());
        String body = SecurityUtils.encryptByBankPublicKey(sortedByKey.getBytes(),publicKeyBank);
        bodyObj.put("body", body);
        // 商户私钥签名
        String signed = SecurityUtils.signByMerchantPrivateKey(sortedByKey.getBytes(),privateKeyMerchant);
        bodyObj.put("sign", signed);
        return bodyObj;
    }

    /**
     * @param json 传入的要排序的json
     * @return 按ascii码排序的json
     */
    public static String sortByKey(String json) {
        Map<String, Object> map = (Map<String, Object>) JSON.parseObject(json, Map.class);
        Map<String, Object> sortedMap = new TreeMap<String, Object>(new MapKeyComparator());
        sortedMap.putAll(map);
        return JSON.toJSONString(sortedMap);
    }
}

class MapKeyComparator implements Comparator<String> {
    public int compare(String st1, String st2) {
        return st1.compareToIgnoreCase(st2);
    }
}
